package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanUtil;
import com.sd365.common.util.StringUtil;
import com.sd365.permission.centre.dao.mapper.CompanyMapper;
import com.sd365.permission.centre.dao.mapper.DictionaryTypeMapper;
import com.sd365.permission.centre.dao.mapper.OrganizationMapper;
import com.sd365.permission.centre.entity.Company;
import com.sd365.permission.centre.entity.DictionaryType;
import com.sd365.permission.centre.entity.Organization;
import com.sd365.permission.centre.pojo.vo.DictionaryCategoryVO;
import com.sd365.permission.centre.service.DictionaryCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>DictionaryTypeService的实现</p>
 *
 * @author 周靖赟
 * @version 1.0
 * @since 12/12/20
 */

/**
 * @author wujiandong
 * @date 2022/08/17 16:34
 * @version 1.0.9
 * @description 修复添加编辑时存在的问题
 */
@Service("dictionaryCategoryService")
public class DictionaryCategoryServiceImpl extends AbstractBaseDataServiceImpl implements DictionaryCategoryService {
    @Autowired
    private DictionaryTypeMapper dictionaryCategoryMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private IdGenerator idGenerator;

    /**
     * <p>DictionaryTypeVO 中设置公司和机构的方法名</p>
     */
    @Override
    public List<DictionaryCategoryVO> commonQuery(DictionaryType dictionaryCategory) {
        // 查找结果为 null 时，返回空的列表
        List<DictionaryCategoryVO> emptyList = new ArrayList<>(0);
        // 查询
        String name = dictionaryCategory.getName();
        if (name == null || StringUtil.isBlank(name)) {
            name = "";
        }
        Example example = new Example(DictionaryType.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("name", String.format("%%%s%%", name));
        example.setOrderByClause("updated_time desc");

        List<DictionaryType> resultList = dictionaryCategoryMapper.selectByExample(example);
        if (resultList == null) {
            return emptyList;
        }

        JSONObject pageInfo = new JSONObject();
        pageInfo.put("total", ((Page) resultList).getTotal());
        pageInfo.put("pages", ((Page) resultList).getPages());
        BaseContextHolder.set("pageInfo", pageInfo.toJSONString());

        // 查询结果不为空，查询机构和公司名
        return BeanUtil.copyList(resultList, DictionaryCategoryVO.class, (src, tar) -> {
            DictionaryType source = (DictionaryType) src;
            DictionaryCategoryVO target = (DictionaryCategoryVO) tar;
            Organization organization = organizationMapper.selectByPrimaryKey(source.getOrgId());
            Company company = companyMapper.selectByPrimaryKey(source.getCompanyId());
            target.setOrgName(organization == null ? "" : organization.getName());
            target.setCompanyName(company == null ? "" : company.getName());
        });
    }

    @Override
    public DictionaryCategoryVO info(@NotNull Long id) {
        DictionaryType dictionaryType = dictionaryCategoryMapper.selectByPrimaryKey(id);
        DictionaryCategoryVO dictionaryTypeVO = BeanUtil.copy(dictionaryType, DictionaryCategoryVO.class);
        // 查询公司和机构名
        Organization organization = organizationMapper.selectByPrimaryKey(dictionaryType.getOrgId());
        Company company = companyMapper.selectByPrimaryKey(dictionaryType.getCompanyId());
        dictionaryTypeVO.setOrgName(organization == null ? "" : organization.getName());
        dictionaryTypeVO.setCompanyName(company == null ? "" : company.getName());
        return dictionaryTypeVO;
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    @Override
    public Boolean add(DictionaryType dictionaryCategory) {
        // 是否有重名
        Example example = new Example(DictionaryType.class);
        example.createCriteria().andEqualTo("name", dictionaryCategory.getName());
        List<DictionaryType> dictionaryCategories = dictionaryCategoryMapper.selectByExample(example);
        if (dictionaryCategories.size() > 0) {
            return false;
        }
        dictionaryCategory.setId(idGenerator.snowflakeId());
        super.baseDataStuff4Add(dictionaryCategory);
        return dictionaryCategoryMapper.insert(dictionaryCategory) > 0;
    }

    @Override
    public Integer modify(DictionaryType dictionaryCategory) {
        // 是否已经有同名类型
        Example example = new Example(DictionaryType.class);
        example.createCriteria().andEqualTo("name", dictionaryCategory.getName())
                .andNotEqualTo("id", dictionaryCategory.getId());
        int nameCount = dictionaryCategoryMapper.selectCountByExample(example);
        if (nameCount > 0) {
            return -1;
        }

        super.baseDataStuff4Updated(dictionaryCategory);
        return dictionaryCategoryMapper.updateByPrimaryKey(dictionaryCategory);
    }

    @Override
    public Boolean delete(DictionaryType dictionaryCategory) {
        return 1 == dictionaryCategoryMapper.deleteByPrimaryKey(dictionaryCategory);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Boolean batchDelete(List<DictionaryType> dictionaryTypeList) {
        int updateCount = 0;
        for (DictionaryType dictionaryType : dictionaryTypeList) {
            updateCount += delete(dictionaryType) ? 1 : 0;
        }

        return updateCount > 0;
    }
}
